import random,logging

from django.http import HttpResponse
from django.shortcuts import render
from celery_tasks.sms import tasks

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from django_redis import get_redis_connection

from meiduo_mall.apps.verifications import constants
from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.yuntongxun.sms import CCP

from .serializers import ImageCodeSerializer

logger = logging.getLogger('django')

# GET /sms_codes/(?P<mobile>1[3-9]\d{9})/?image_code_id=xxx&text=xxx
class SmsCodeView(GenericAPIView):
    '''实现短信验证码接口'''
    serializer_class = ImageCodeSerializer
    '''接收参数：mobile，image_code_id,text'''
    '''校验参数
       比较图形验证码的一致性
    '''
    def get(self, request, mobile):
        # 判断图形验证码
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True )
        # 生成随机短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        # 调用第三方云通讯发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES//60], 1)
        # 调用celery中的发送短信任务任务，
        tasks.send_sms_code.delay(mobile,sms_code)

        # 存储短信验证码到redis
        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.set('sms_%s' % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
        # redis_conn.set("send_flag_%s" % mobile,1 ,constants.SEND_SMS_CODE_INTERVAL)

        # 运用管道的方法查询redis，能够提高执行效率
        pl = redis_conn.pipeline()
        pl.set('sms_%s' % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
        pl.set("send_flag_%s" % mobile,1 ,constants.SEND_SMS_CODE_INTERVAL)
        pl.execute()

        # 返回响应数据
        return Response({'message':'OK,发送成功'})


class ImageCodeAPIView(APIView):
    ''' 实现图形验证码接口 '''
    def get(self,request,image_code_id):
        # 生成图片验证码的内容和图片
        text,image = captcha.generate_captcha()
        logger.info(text)
        # 把图片验证码的uuid编号和图片验证码的内容存储进redis缓存
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.set('img_%s'% image_code_id, text, constants.IMAGE_CODE_REDIS_EXPIRES)
        # 返回图片相应数据给前端
        return HttpResponse(image , content_type='image/jpg')




